package com.angeho.lawyer.controller;

import com.alibaba.fastjson.JSONObject;
import com.angeho.entity.CallDetailVo;
import com.angeho.lawyer.service.CallDetailService;
import com.angeho.util.Consts;
import com.angeho.util.HttpClientUtil;
import com.angeho.vo.CallDetailParam;
import com.angeho.vo.OrderInfo;
import com.angeho.vo.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import javax.validation.constraints.NotBlank;
import java.time.Duration;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/ly")
@Slf4j
@Validated
public class ApiController {
    @Autowired
    RedisTemplate<String,Object> redisTemplate;
    @Value("${com.bonatone.ext-api.appKey}")
    String appkey;
    @Value("${com.bonatone.ext-api.appSecret}")
    String appsecret;
    @Value("${com.bonatone.ext-api.baseUrl}")
    String baseUrl;
    @Autowired
    CallDetailService callDetailService;


    @RequestMapping("/test")
    public R test(){
        return R.ok().put("message","服务已运行");
    }
    @RequestMapping("getToken")
    public R getToken(){
        String redisKey="token:"+appkey;
        if(redisTemplate.hasKey(redisKey)){
          String  token= (String) redisTemplate.opsForValue().get(redisKey);
          return R.ok().setData(token);
        }
        String reqUrl=baseUrl+"/dockingSupport/getToken?appKey="+appkey+"&appSecret="+appsecret;
        Map<String,String> header=new HashMap<>();
        header.put("content-type","application/json;charset=utf-8");
        String resultStr=HttpClientUtil.post(reqUrl,new HashMap<>(),header,"utf-8","utf-8");
        log.info("getToken-> :{}",resultStr);
        JSONObject result=JSONObject.parseObject(resultStr);
        if("000000".equals(result.getString("code"))){
            String  token= (String) result.get("token");
            redisTemplate.opsForValue().set(redisKey,token, Duration.ofHours(10L));
            return R.ok().setData(token);
        }else {
            return R.fail(result.getString("message"));
        }
    }

    @PostMapping("order-callback")
    public R setOrderCallBack(@RequestBody @Valid  OrderInfo orderParam){
        Map<String,String> status=new HashMap<>();
        R result=new R();
        log.info("用户接单-> :{}",orderParam);
        try {
            redisTemplate.opsForZSet().add(Consts.ORDER_INF_TM, orderParam.getUcid(), System.currentTimeMillis());
            redisTemplate.opsForHash().put(Consts.ORDER_INF_KEY,
                    orderParam.getUcid(), orderParam);
            status.put("desp","成功");
            status.put("code","1");
        }catch (Exception e){
            status.put("desp",e.getMessage());
            status.put("code","0");
        }
        return result.put("status",status);
    }
    @RequestMapping("order-getOrderInfo/{callId}")
    public R getOrderInfo(@NotBlank(message = "callID不能为空") @PathVariable String callId){
        if(!redisTemplate.hasKey(Consts.ORDER_INF_KEY)){
            return R.fail("订单不存在").setCode(404);
        }
        OrderInfo orderInfo=(OrderInfo) redisTemplate.opsForHash().get(Consts.ORDER_INF_KEY,callId);
        if(orderInfo==null){
            return R.fail("订单不存在").setCode(404);
        }
        log.info("getOrderInfo-> :{}",orderInfo);
        redisTemplate.opsForZSet().remove(Consts.ORDER_INF_TM,callId);
        redisTemplate.opsForHash().delete(Consts.ORDER_INF_KEY,callId);
        return R.ok().setData(orderInfo);
    }
    @RequestMapping("call-detail")
    public R getOrderInfo(@RequestBody  CallDetailParam callDetailParam){
        CallDetailVo callDetailVo=callDetailService.queryCallDetailByParam(callDetailParam);
        R r=new R();
        Map<String,String> status=new HashMap<>();
        status.put("desp","成功");
        status.put("code","1");
        r.put("status",status).put("result",callDetailVo);
        return r;
    }
}
